# -*- coding: utf-8 -*-
"""
Created on Thu Aug  9 13:38:54 2018

@author: jiujiujiu
"""
import requests
import time
import json
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def getHTMLText(url):
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    try:
        r = requests.get(url, timeout=30, headers=header)
        r.raise_for_status()  # 如果状态不是200, 引发HTTPError异常
        r.encoding = r.apparent_encoding
        html = r.text
        return html

    except:
        return None


def get_datelist(url):
    l = []
    d = getHTMLText(url)
    if d:
        d = json.loads(d)
        content = d['content']
        for x in content:
            if 'createDate' in x.keys():
                s = str(x['createDate'])[:-3]
                date = time.strftime("%Y-%m-%d %X", time.localtime(int(s)))[:10]
                l.append(date)
    #    print(l)
    return l


def get_datelist_1(url):
    l = []
    d = getHTMLText(url)
    if d:
        d = json.loads(d)
        content = d['content']
        for x in content:
            if 'createDate' in x.keys():
                date = str(x['createDate'])[:10]
                l.append(date)
    return l


def count_process_one():  # 资讯
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        s = d1 + d2 + d3
        url = 'http://www.block18.io/api/newArticle/{}/15'
        url = url.format(a)
        datelist = get_datelist(url)
        if not datelist:
            break
        print('----18区资讯第{}页获取中----'.format(a))
        for date in datelist:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_two():  # 快讯
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        s = d1 + d2 + d3
        url = "http://www.block18.io/api/newsList/{}/iOS"
        url = url.format(a)
        datelist = get_datelist(url)
        if not datelist:
            break
        print('----18区快讯第{}页获取中----'.format(a))
        for date in datelist:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '18区'
    t1 = count_process_one()
    t2 = count_process_two()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
